package com.fandou.speech.wakeup.baidu;

import android.os.Bundle;
import android.os.Message;

import com.baidu.aip.asrwakeup3.core.recog.IStatus;
import com.baidu.aip.asrwakeup3.core.recog.MyRecognizer;
import com.baidu.aip.asrwakeup3.core.recog.listener.IRecogListener;
import com.baidu.aip.asrwakeup3.core.recog.listener.MessageStatusRecogListener;
import com.baidu.aip.asrwakeup3.core.util.MyLogger;
import com.baidu.aip.asrwakeup3.core.wakeup.listener.IWakeupListener;
import com.baidu.aip.asrwakeup3.core.wakeup.listener.RecogWakeupListener;
import com.baidu.speech.asr.SpeechConstant;
import com.blankj.utilcode.util.LogUtils;
import com.fandou.speech.R;
import com.fandou.speech.tts.baidu.Speaker;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 唤醒后识别 本例可与ActivityWakeUp 对比作为集成识别代码的参考
 */
public abstract class WakeUpRecogActivity extends WakeUpActivity implements IStatus, MessageStatusRecogListener.OnAsrListener {


    private static final String TAG = "WakeUpRecogActivity";

    /**
     * 识别控制器，使用MyRecognizer控制识别的流程
     */
    protected MyRecognizer myRecognizer;

    protected Speaker speaker;

    /**
     * 0: 方案1， backTrackInMs > 0,唤醒词说完后，直接接句子，中间没有停顿。
     * 开启回溯，连同唤醒词一起整句识别。推荐4个字 1500ms
     * backTrackInMs 最大 15000，即15s
     * <p>
     * >0 : 方案2：backTrackInMs = 0，唤醒词说完后，中间有停顿。
     * 不开启回溯。唤醒词识别回调后，正常开启识别。
     * <p>
     */
    private int backTrackInMs = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IRecogListener recogListener = new MessageStatusRecogListener(this);
        // 改为 SimpleWakeupListener 后，不依赖handler，但将不会在UI界面上显示
        myRecognizer = new MyRecognizer(this, recogListener);

        speaker = new Speaker();
        speaker.initialTts(getApplicationContext());

        IWakeupListener listener = new RecogWakeupListener(handler);
        myWakeup.setEventListener(listener); // 替换原来的 listener

    }

    @Override
    protected void handleMsg(Message msg) {
        super.handleMsg(msg);
        log("handleMsg: " + msg.what);
//        if (msg.what == STATUS_WAKEUP_SUCCESS) { // 唤醒词识别成功的回调，见RecogWakeupListener
//            speaker.startTts("在", () -> {
//                startAsr();
//            });
//        }
    }

    @Override
    public void onAsrBegin() {
        LogUtils.d("onAsrBegin:用户开始说话 ");
    }

    @Override
    public void onAsrEnd() {
        LogUtils.d("onAsrEnd ");
    }


    @Override
    public void updateVolume(int volumePercent, int volume) {
        LogUtils.d("updateVolume: " + volume + ",volumePercent:" + volumePercent);
    }

    @Override
    public void onAsrResult(String res) {
        LogUtils.d("onAsrResult: " + res);
    }


    @Override
    public void onAsrError(int errorCode, int subErrorCode, String errorMsg) {
        LogUtils.d("onAsrError: " + errorCode + " -- " + subErrorCode + " -- " + errorMsg);
//        showErrorToast("onAsrError: " + errorCode + " -- " + subErrorCode + " -- " + errorMsg);
    }


    /**
     * 执行语音识别
     */
    public void startAsr() {
        // 此处 开始正常识别流程
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, true);
        params.put(SpeechConstant.VAD, SpeechConstant.VAD_DNN);
        params.put(SpeechConstant.ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH, "assets://baidu_speech_grammar.bsg");
        // 使用1537中文模型。其它PID参数请看文档
//        params.put(SpeechConstant.PID, 1537);
        params.put(SpeechConstant.PID, 15373);
        params.put(SpeechConstant.NLU, "enable");
        params.put(SpeechConstant.DECODER, 2);

        params.put(SpeechConstant.SOUND_START, R.raw.bdspeech_recognition_start);
        params.put(SpeechConstant.SOUND_END, R.raw.bdspeech_speech_end);
        params.put(SpeechConstant.SOUND_SUCCESS, R.raw.bdspeech_recognition_success);
        params.put(SpeechConstant.SOUND_ERROR, R.raw.bdspeech_recognition_error);
        params.put(SpeechConstant.SOUND_CANCEL, R.raw.bdspeech_recognition_cancel);

        if (backTrackInMs > 0) {
            // 方案1  唤醒词说完后，直接接句子，中间没有停顿。开启回溯，连同唤醒词一起整句识别。
            // System.currentTimeMillis() - backTrackInMs ,  表示识别从backTrackInMs毫秒前开始
            params.put(SpeechConstant.AUDIO_MILLS, System.currentTimeMillis() - backTrackInMs);
        }
        myRecognizer.cancel();
        myRecognizer.start(params);
    }


    @Override
    protected void stop() {
        super.stop();
        myRecognizer.stop();
    }

    @Override
    protected void onDestroy() {
        speaker.releaseTts();
        myRecognizer.release();
        super.onDestroy();
    }

    private void log(String log) {
        MyLogger.info(TAG, log);
    }
}
